from django.http import JsonResponse

from utils import requests_pro
from rest_framework.views import  APIView
from lxml import etree
from utils import orm
orm.orm_standby()
from dal import models

class TiYuRequests(APIView):
    def get(self,request):
        message = {}
        try:
            session =requests_pro.session_requests_b()

            page = session.get(url="https://news.baidu.com/sports")

            page.encoding = page.apparent_encoding

            page_text =page.text

            tree = etree.HTML(page_text)

            li_list = tree.xpath('//*[@id="col_focus"]/div[1]/div[1]/ul[1]/li')


            for li in li_list:
    
                title = li.xpath("./a/text()")[0]
                url = li.xpath("./a/@href")[0]

                if models.TiYu.objects.filter(title=title).exists() == False:
                    models.TiYu.objects.create(title=title,url=url)

            message['code'] = 200
            message['message'] = "更新成功"
            return JsonResponse(message)
        except Exception as e:
            print(e)
            message['code'] = 444
            message['message'] = "更新失败"
            return JsonResponse(message)
